package com.cloudauth.authgateway.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
@description jwt工具类
@author wbs
**/
public class JwtUtil {

    public static final String SECRET = "qazwsx123444$#%#()*&& asdaswwi1235 ?;!@#kmmmpom in***xx**&";
    public static final String TOKEN_PREFIX = "Bearer";
    public static final String HEADER_AUTH = "Authorization";


    /**
     *  生成token
     * @param param 需要储存的信息
     * @param secret 秘钥
     * @return
     */
    public static String generateToken(Map<String,Object> param,String secret){

        String jwtTokenStr = Jwts.builder().setSubject("customer_info").setClaims(param)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        return jwtTokenStr;
    }


    /**
     *  解析token
     * @param token 需要解析的token
     * @param secret 秘钥
     * @return
     */

    public static Map<String,String> validateToken(String token,String secret){

        HashMap<String, String> resultMap = new HashMap<>();

        if (!StringUtils.isBlank(token)){

            Map<String,Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
//            body.forEach((k,v)->{
//                resultMap.put(k,(String) v);
//            });

            String id = String.valueOf(body.get("id"));
            String user = (String) body.get("user");

            resultMap.put("id",id);
            resultMap.put("user",user);

            if (StringUtils.isEmpty(user)){
                throw new PermissionException("user is error,please check");
            }
            return resultMap;
        }else{
            throw new PermissionException("token is error,please check");
        }

    }


}
